package bank

var addChannel = make(chan int)       //增加余额的channel
var balanceChannel = make(chan int)   //查询余额的channel
var initChannel = make(chan struct{}) //初始化余额的channel

func Add(amount int) {
	addChannel <- amount
}
func Balance() int {
	return <-balanceChannel
}

func Init() {
	initChannel <- struct{}{}
}

func teller() {
	var balance int //余额仅限于这个goroutine
	for {
		//如果没有 case 可运行，它将阻塞
		select { //每个 case 必须是一个通信操作
		case amount := <-addChannel:
			balance += amount
		case balanceChannel <- balance:
		case <-initChannel:
			balance = 0
		}
	}
}

func init() {
	go teller() //启动一个收纳员
}
